package com.jt.service;

import com.jt.pojo.ImageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@PropertySource("classpath:/properties/image.properties")
@Service
public class FileServiceImpl implements FileService{

    @Value("${image.fileLocalDir}")
    private String fileLocalDir;
    @Value("${image.urlPath}")
    private String urlPath;

    private static Set<String> TypeSet=new HashSet<>();
    static {
        TypeSet.add(".jpg");
        TypeSet.add(".png");
        TypeSet.add(".gif");
    }
    @Override
    public ImageVO upload(MultipartFile uploadFile) {
        String fileName=uploadFile.getOriginalFilename();
        int index=fileName.lastIndexOf(".");
        String fileType=fileName.substring(index);
        fileType=fileType.toLowerCase();
        if (!TypeSet.contains(fileType)){
            return ImageVO.fail();
        }

        try {
            BufferedImage bufferedImage= ImageIO.read(uploadFile.getInputStream());
            int width=bufferedImage.getWidth();
            int height=bufferedImage.getHeight();
            if (width==0||height==0){
                return ImageVO.fail();
            }
            String dateDir=new SimpleDateFormat("/yyyy/MM/dd/")
                    .format(new Date());
            String fileDir=fileLocalDir+dateDir;
            File imageFileDir =new File(fileDir);
            if (!imageFileDir.exists()){
                imageFileDir.mkdirs();
            }
            String uuid=
                    UUID.randomUUID().toString().replace("-", "");
            String realFileName=uuid+fileType;

            String realFilePath=fileDir+realFileName;
            File realFile=new File(realFilePath);
            uploadFile.transferTo(realFile);
            String url=urlPath+dateDir+realFileName;
            return ImageVO.success(url,width,height);
        }catch (IOException e){
            e.printStackTrace();
            return ImageVO.fail();
        }
    }
}
